package cn.com.bonc.khjy.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @author BTW
 */
public class RestUtil {

    private static Log log = LogFactory.get();

    public static String sendPostRequest( String url, List paramList ) {
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        try ( CloseableHttpClient httpClient = HttpClients.createDefault() ) {
            httpPost = new HttpPost( url );
            httpPost.setEntity( new UrlEncodedFormEntity( paramList, "utf-8" ) );
            response = httpClient.execute( httpPost );
            String result = EntityUtils.toString( response.getEntity(), "utf-8" );
            if ( StrUtil.isBlank( result ) ) {
                return "error";
            } else {
                return result;
            }
        } catch ( IOException e ) {
            log.error( e, SystemMessageId.CMP0971, url, e.getMessage() );
            return "error";
        } finally {
            try {
                response.close();
                httpPost.completed();
            } catch ( IOException e ) {
                log.error( e, SystemMessageId.CMP0972, url, e.getMessage() );
            }
        }
    }

    public static String sendGetRequest( String url, List paramList ) {
        HttpGet httpGet = null;
        CloseableHttpResponse response = null;
        try (CloseableHttpClient httpClient = HttpClients.createDefault()){
            URIBuilder uriBuilder = new URIBuilder(url);
            uriBuilder.setParameters( paramList );
            httpGet = new HttpGet( uriBuilder.build() );
            response = httpClient.execute( httpGet );
            String result = EntityUtils.toString( response.getEntity(), "utf-8" );
            if ( StrUtil.isBlank( result ) ) {
                return "error";
            } else {
                return result;
            }
        } catch ( IOException e ) {
            log.error( e, SystemMessageId.CMP0971, url, e.getMessage() );
            return "error";
        } catch ( URISyntaxException e ) {
            log.error( e, SystemMessageId.CMP0973, url, paramList,e.getMessage() );
            return "error";
        } finally {
            try {
                response.close();
                httpGet.completed();
            } catch ( IOException e ) {
                log.error( e, SystemMessageId.CMP0972, url, e.getMessage() );
            }
        }
    }
}
